package lzy.util;

import java.sql.*;
import java.util.*;

public class ManualDataFiller {
    // 数据库连接信息（请根据实际情况修改）
    private static final String URL = "jdbc:mysql://localhost:3306/ginseng_system?useSSL=false&serverTimezone=Asia/Shanghai";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    // 需要补充的表
    private static final List<String> TABLES = Arrays.asList(
            "user", "batch", "processing_equipment", "farm_operation", "quality_inspection", "ginseng",
            "base", "planting_record", "environment_data", "crop_status", "pest_detection", "processing_step", "traceability_code"
    );

    public static void main(String[] args) throws Exception {
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            for (String table : TABLES) {
                try {
                    fillTable(conn, table);
                    System.out.println("表 " + table + " 自动补充一条数据");
                    Thread.sleep(20000); // 每20秒补充一条
                } catch (Exception e) {
                    System.err.println("补充表 " + table + " 失败: " + e.getMessage());
              }
            }
        }
    }

    private static void fillTable(Connection conn, String tableName) throws SQLException {
        List<Map<String, Object>> columns = new ArrayList<>();
        try (PreparedStatement ps = conn.prepareStatement(
                "SELECT COLUMN_NAME, DATA_TYPE, COLUMN_TYPE, EXTRA FROM information_schema.COLUMNS WHERE table_schema=DATABASE() AND table_name=?")) {
            ps.setString(1, tableName);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Map<String, Object> col = new HashMap<>();
                    col.put("COLUMN_NAME", rs.getString("COLUMN_NAME"));
                    col.put("DATA_TYPE", rs.getString("DATA_TYPE"));
                    col.put("COLUMN_TYPE", rs.getString("COLUMN_TYPE"));
                    col.put("EXTRA", rs.getString("EXTRA"));
                    columns.add(col);
                }
            }
        }
        StringBuilder fields = new StringBuilder();
        StringBuilder values = new StringBuilder();
        List<Object> params = new ArrayList<>();

        for (Map<String, Object> col : columns) {
            String name = (String) col.get("COLUMN_NAME");
            String type = (String) col.get("DATA_TYPE");
            String colType = (String) col.get("COLUMN_TYPE");
            String extra = (String) col.get("EXTRA");
            if ("auto_increment".equalsIgnoreCase(extra)) continue;
            if ("batch_no".equalsIgnoreCase(name) && tableName.equals("batch")) continue;
            fields.append(name).append(",");
            values.append("?,");
            params.add(randomValue(type, colType));
        }
        if (fields.length() == 0) return;
        fields.setLength(fields.length() - 1);
        values.setLength(values.length() - 1);

        String sql = String.format("INSERT INTO %s (%s) VALUES (%s)", tableName, fields, values);
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            for (int i = 0; i < params.size(); i++) {
                ps.setObject(i + 1, params.get(i));
            }
            ps.executeUpdate();
        }
    }

    private static Object randomValue(String type, String colType) {
        Random r = new Random();
        switch (type) {
            case "varchar": return "test" + r.nextInt(10000);
            case "int": case "bigint": return r.nextInt(10000);
            case "decimal": return Math.round(r.nextDouble() * 10000) / 100.0;
            case "datetime": case "timestamp": return new Timestamp(System.currentTimeMillis());
            case "enum":
                String enums = colType.substring(colType.indexOf("(") + 1, colType.indexOf(")"));
                String[] opts = enums.replace("'", "").split(",");
                return opts[r.nextInt(opts.length)];
            case "text": return "备注" + r.nextInt(10000);
            case "date": return new java.sql.Date(System.currentTimeMillis());
            default: return null;
        }
    }
} 